package thread;
class Counter2{
    private int count = 0;
    void add(){
        count++;
    }
    int get(){
        return count;
    }
}

public class Demo21 {
    public static void main(String[] args) throws InterruptedException {
        Counter2 counter2 = new Counter2();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized (counter2){
                    counter2.add();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                synchronized (counter2){//如果t2没加锁意味着即使t1加锁了，t2执行过程中没有任何阻塞，没有互斥。
                    counter2.add();     //仍然会使t1++一半的时候，被t2进来把结果覆盖掉
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count = " + counter2.get());
    }
}
